package com.h.cheng.pselector.base.load;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.h.cheng.pselector.R;
import com.h.cheng.pselector.bean.BaseMedia;
import com.h.cheng.pselector.ui.FileViewActivity;
import com.h.cheng.pselector.ui.ImgSelectorActivity;
import com.h.cheng.pselector.ui.ImgViewActivity;
import com.h.cheng.pselector.ui.VideoSelectorActivity;
import com.h.cheng.pselector.utils.AppUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者： ch
 * 时间： 2018/4/9 0009-下午 4:55
 * 描述：
 * 来源：
 */


public class PSManager {
    private static PSManager manager;
    private PSConfig mConfig;
    private PopupWindow pop;
    private static boolean isUseSysAlbum;
    private static String path;


    /**
     * 拍照
     */
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 10000;
    /**
     * 从相册选择
     */
    private static final int REQUEST_CODE_PICK_IMAGE = 10001;
    /**
     * 相册多选
     */
    private static final int REQUEST_CODE_PICK_IMAGE_MULT = 10002;
    /**
     * 视频 多选
     */
    private static final int REQUEST_CODE_VIDEO_MULT = 10003;


    private String basePath;
    private static Uri photoUri;


    public static PSManager getInstance() {
        if (manager == null) {
            manager = PSManager.of();
        }
        return manager;
    }

    public PSManager(PSConfig mConfig) {
        this.mConfig = mConfig;
    }

    public PSConfig getmConfig() {
        return mConfig;
    }

    public void setmConfig(PSConfig mConfig) {
        this.mConfig = mConfig;

    }

    public static PSManager of() {
        PSConfig config = new PSConfig().withMaxCount(1).withSpanCount(3);
        manager = new PSManager(config);
        return manager;
    }

    public static PSManager of(PSConfig config) {
        manager = new PSManager(config);
        return manager;
    }

    /**
     * 大图预览
     *
     * @param context
     * @param list
     * @param postion
     */
    public void forPreView(Context context, ArrayList<BaseMedia> list, int postion) {

        if (context instanceof Activity) {
            if (!AppUtils.checkPremission((Activity) context, PSConfig.REQUEST_CODE_PREVIEW, Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE))
                return;
        }


        Intent intent = new Intent(context, ImgViewActivity.class);
        intent.putParcelableArrayListExtra(PSConfig.IMG_CONTENT, list);
        intent.putExtra(PSConfig.IMG_POSITION, postion);
        context.startActivity(intent);

        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.activity_zoom_open, 0);
        }

    }

    /**
     * 大图预览
     *
     * @param context
     * @param list
     */
    public void forPreView(Context context, ArrayList<BaseMedia> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        forPreView(context, list, 0);

    }

    /**
     * 大图预览
     *
     * @param context
     * @param path
     */
    public void forPreView(Context context, String... path) {
        if (path == null || path.length == 0) {
            return;
        }

        ArrayList<BaseMedia> list = new ArrayList<>();
        for (String pa : path) {
            list.add(new BaseMedia(pa, pa, "0"));
        }
        forPreView(context, list, 0);
    }

    /**
     * 视频
     *
     * @param activity
     */
    public void forVideoView(Activity activity) {
        if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_VIDEO, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE))
            return;

        Intent intent = new Intent(activity, VideoSelectorActivity.class);
        activity.startActivityForResult(intent, REQUEST_CODE_VIDEO_MULT);
    }

    /**
     * 文件选择
     *
     * @param context
     */
    public void forFileView(Context context) {
        forFileView(context, "");
    }

    /**
     * 文件选择
     *
     * @param context
     */
    public void forFileView(Context context, String path) {
        PSManager.path = path;
        if (context instanceof Activity) {
            if (!AppUtils.checkPremission((Activity) context, PSConfig.REQUEST_CODE_FILE, Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE))
                return;
        }


        Intent intent = new Intent(context, FileViewActivity.class);
        intent.putExtra(PSConfig.FILE_PATH, path);
        context.startActivity(intent);
    }

    /**
     * 打开相册
     *
     * @param activity
     */
    public void forAlbum(Activity activity) {
        if (activity == null) {
            return;
        }
        isUseSysAlbum = getmConfig().isUseSysAlbum();
        if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE))
            return;

        if (getmConfig().isUseSysAlbum()) {
            getImageFromAlbum(activity);// 从相册里获取
        } else {

            activity.startActivityForResult(new Intent(activity, ImgSelectorActivity.class), REQUEST_CODE_PICK_IMAGE_MULT);
        }

    }


    /**
     * 打开相册
     *
     * @param activity
     * @param isUseSysAlbum
     */
    public void forAlbum(Activity activity, boolean isUseSysAlbum) {
        if (activity == null) {
            return;
        }
        PSManager.isUseSysAlbum = isUseSysAlbum;

        if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE))
            return;

        if (isUseSysAlbum) {
            getImageFromAlbum(activity);// 从相册里获取
        } else {
            activity.startActivityForResult(new Intent(activity, ImgSelectorActivity.class), REQUEST_CODE_PICK_IMAGE_MULT);
        }

    }

    /**
     * 打开相机、相册 选择框
     *
     * @param activity
     * @param parent
     */
    public void forDialog(Activity activity, View parent) {

        basePath = Environment.getExternalStorageDirectory() + "/ledashop/img/";
        View view = LayoutInflater.from(activity).inflate(R.layout.popw_alert_select_phone, null);
        initView(activity, view);
        pop = new PopupWindow(activity);
        pop.setContentView(view);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        pop.setBackgroundDrawable(dw);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }
                return false;
            }
        });
        pop.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    private void initView(Activity activity, View view) {
        TextView tv_photograph = view.findViewById(R.id.tv_photograph);
        TextView tv_album = view.findViewById(R.id.tv_album);
        LinearLayout ll_cancle_layout = view.findViewById(R.id.ll_cancle_layout);
        tv_photograph.setOnClickListener(new MyOnClickListener(activity));
        tv_album.setOnClickListener(new MyOnClickListener(activity));
        ll_cancle_layout.setOnClickListener(new MyOnClickListener(activity));
    }


    private class MyOnClickListener implements View.OnClickListener {

        private Activity activity;

        public MyOnClickListener(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void onClick(View v) {
            int i = v.getId();
            if(i == R.id.tv_record_video){
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }

                if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_CAMEIA, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE))
                    return;
                forVideoView(activity);
            }
            else if (i == R.id.tv_photograph) {


                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }

                if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_CAMEIA, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE))
                    return;

                forCamera(activity);

                // 相册
            } else if (i == R.id.tv_album) {

                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }

                if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_SYS_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE))
                    return;

                forAlbum(activity, getmConfig().isUseSysAlbum());


                // 取消
            } else if (i == R.id.ll_cancle_layout) {
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }

            } else {
            }
        }
    }

    /**
     * 从系统相册里选取
     */
    public void getImageFromAlbum(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    /**
     * 系统相机
     */
    public void forCamera(Activity activity) {

        if (!AppUtils.checkPremission(activity, PSConfig.REQUEST_CODE_CAMEIA, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE))
            return;

        Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
        String state = Environment.getExternalStorageState();
        // 检查是否有存储卡
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 创建位置
            if (TextUtils.isEmpty(basePath)) {
                basePath = Environment.getExternalStorageDirectory() + "/ledashop/img/";
            }
            File fileDir = new File(basePath);
            if (!fileDir.exists()) {// 目录是否存在
                fileDir.mkdirs();
            }

            File file = new File(basePath + System.currentTimeMillis() + ".jpg");
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

                photoUri = Uri.fromFile(file);
                // Create path for temp file
                // 相机存储的地址
            } else {
                photoUri = FileProvider.getUriForFile(activity, AppUtils.getAppPackageName(activity) + ".FileProvider", file);
                getImageByCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            activity.startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);// 拍照完送去裁剪
        }

    }

    /**
     * 获取结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     * @param activity
     * @param callBack
     */
    public static void getResult(int requestCode, int resultCode, Intent data, Activity activity, ResultCallBack callBack) {
        if (resultCode == -1) {
            if (requestCode == REQUEST_CODE_PICK_IMAGE) {
                //相册
                if (null != data) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        if (uri.getPath().startsWith("/external/") || uri.getPath().startsWith("/raw/")) {
                            String path = AppUtils.getFilePathFromContentUri(uri, activity.getContentResolver());
                            if (callBack != null) {
                                callBack.formSysAlbum(path);
                            }
                        } else {
                            if (callBack != null) {
                                callBack.formSysAlbum(uri.getPath());
                            }
                        }
                    }
                }

            } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA) {
                //相机

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    if (callBack != null) {
                        callBack.formCamera(photoUri.getPath());
                    }
                } else {
                    String url = photoUri.getPath();
                    if (url.contains("camera.photos")) {
                        String base = Environment.getExternalStorageDirectory().getPath();
                        if (callBack != null) {
                            callBack.formCamera(base + url.substring(url.indexOf("camera.photos") + 13));
                        }
                    }
                }
            } else if (requestCode == REQUEST_CODE_PICK_IMAGE_MULT) {
                //相册多选
                if (data != null) {
                    ArrayList<BaseMedia> list = data.getParcelableArrayListExtra(PSConfig.IMG_CONTENT);
                    if (callBack != null) {
                        callBack.formMultAlbm(list);
                    }
                } else {
                    if (callBack != null) {
                        callBack.formMultAlbm(new ArrayList<BaseMedia>());
                    }
                }
            }

        }

    }

    public static void getPermissionResult(final Activity activity, int requestCode, String[] permissions, int[] grantResults) {
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantPermissions) {
                if (requestCode == PSConfig.REQUEST_CODE_CAMEIA) {
                    PSManager.getInstance().forCamera(activity);
                } else if (requestCode == PSConfig.REQUEST_CODE_SYS_ALBUM) {
                    PSManager.getInstance().forAlbum(activity, isUseSysAlbum);
                } else if (requestCode == PSConfig.REQUEST_CODE_ALBUM) {
                    PSManager.getInstance().forAlbum(activity, isUseSysAlbum);
                } else if (requestCode == PSConfig.REQUEST_CODE_PREVIEW) {
                    PSManager.getInstance().forPreView(activity);
                } else if (requestCode == PSConfig.REQUEST_CODE_VIDEO) {
                    PSManager.getInstance().forVideoView(activity);
                } else if (requestCode == PSConfig.REQUEST_CODE_FILE) {
                    PSManager.getInstance().forFileView(activity, path);
                }
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedPermissions) {
                if (AndPermission.hasAlwaysDeniedPermission(activity, deniedPermissions)) {
                    // 第一种：用默认的提示语。
                    AndPermission.defaultSettingDialog(activity, 300).show();

                    // 第二种：用自定义的提示语。
                    // AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
                    // .setTitle("权限申请失败")
                    // .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    // .setPositiveButton("好，去设置")
                    // .show();

                    // 第三种：自定义dialog样式。
                    // SettingService settingService =
                    //    AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
                    // 你的dialog点击了确定调用：
                    // settingService.execute();
                    // 你的dialog点击了取消调用：
                    // settingService.cancel();
                }
            }
        });
    }

    /**
     * @param resolver
     * @param bucketId
     * @param page
     * @param callBack
     */
    public void loadImageMedia(ContentResolver resolver, String bucketId, int page, IMediaCallBack<BaseMedia> callBack) {
        new ImageTask(callBack, resolver, page, bucketId).execute(0);
    }

    /**
     * @param resolver
     * @param bucketId
     * @param page
     * @param callBack
     */
    public void loadVideoMedia(ContentResolver resolver, String bucketId, int page, IMediaCallBack<BaseMedia> callBack) {
        new VideoTask(callBack, resolver, page, bucketId).execute(0);
    }


    public interface IMediaCallBack<T> {
        void postMedia(@Nullable List<T> medias, int count);
    }

    public interface ResultCallBack {
        void formCamera(String path);

        void formSysAlbum(String path);

        void formMultAlbm(ArrayList<BaseMedia> list);

    }


}
